package reflect;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URISyntaxException;
/**
 * 自动调用与当前类Test2同一个包中那些类的所有公开的无参方法.
 */
public class Test2 {
    public static void main(String[] args) throws URISyntaxException, ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException {
        //定位编译后当前类所在目录
        File dir = new File(Test2.class.getResource(".").toURI());
        //class.getClassLoader().getResource(".").toURI()   D:\tedu\gudiwen\JSD2206_SE\out\production\JSD2206_SE
        //class.getResource(".").toURI()   D:\tedu\gudiwen\JSD2206_SE\out\production\JSD2206_SE\reflect
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for(File file : subs){
            String name =file.getName();
            //依据.class文件名获取类名
            String className = name.substring(0,name.indexOf('.'));
            //加载类对象
            Class cls = Class.forName(Test2.class.getPackage().getName()+"."+className);
            Object obj = cls.newInstance();
            System.out.println("实例化对象:"+cls.getSimpleName());
            Method[] methods = cls.getDeclaredMethods();
            for(Method method : methods){
                //运行公开无参,方法名含s的方法
                if (method.getParameterCount() == 0 && method.getModifiers() == Modifier.PUBLIC && method.getName().contains("s")){
                    System.out.println("自动调用:"+method.getName());
                    method.invoke(obj);
                }
            }
        }
    }
}
